/*
 * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.laikan.reader.bookstore.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookstart.activity.HomeActivity;
import com.laikan.reader.bookstore.fragment.SuperAwesomeCardFragment;
import com.laikan.reader.bookstore.view.PagerSlidingTabStrip;
import com.umeng.analytics.MobclickAgent;

public class RecommendActivity extends BasicActivity implements OnClickListener {

    public ViewPager pager;
    private PagerSlidingTabStrip tabs;
    private MyPagerAdapter adapter;
    private int currentColor = 0xFF666666;
    private TextView popwin;
    private RelativeLayout linear;
    private LinearLayout ll_search_img;
    private String[] channel, book_channels = {"推荐", "特价", "排行", "分类", "专题"}, other = {"推荐", "免费", "排行", "分类", "完本"};
    private YourListener mYourListener = null;
    private LinearLayout linean_pop;
    private HomeActivity homeActivity;
    private RadioButton mFstBtn;
    private RadioButton mSndBtn;
    private RadioButton mThdBtn;
    private long mkeyTime;

    private void choiceState(int state) {
        if (state == 1) {
            mFstBtn.setChecked(true);
            mSndBtn.setChecked(false);
            mThdBtn.setChecked(false);
        }else if (state == 2) {
            mFstBtn.setChecked(false);
            mSndBtn.setChecked(true);
            mThdBtn.setChecked(false);

        }else if (state == 3) {
            mFstBtn.setChecked(false);
            mSndBtn.setChecked(false);
            mThdBtn.setChecked(true);

        }
    }

    @Override
    protected void onResume() {

        super.onResume();
        if (SPUtil.getBoolean("refresh_tab", false)) {
            Intent intent = new Intent();
            intent.setClass(mContext, CateRankActivity.class);
            intent.putExtra("mHtmlUrl", SPUtil.getString("refresh_zt_url", ""));
            intent.putExtra("mode", "special");
            intent.putExtra("title", SPUtil.getString("refresh_zt_title", ""));
            startActivity(intent);
            SPUtil.putBoolean("refresh_tab", false);
        }

        if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            ((InputMethodManager)RecommendActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(RecommendActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            // 隐藏软键盘
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        }
        int type = SPUtil.getInt("select_setting", 1);
        switch (type) {
            case 1:
                popwin.setText(channel[0]);
                break;
            case 2:
                popwin.setText(channel[1]);
                break;
            case 3:
                popwin.setText(channel[2]);
                break;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 2秒内连续按两次 退出程序
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mkeyTime) > 2000) {
                mkeyTime = System.currentTimeMillis();
                Toast.makeText(this, R.string.personal_exit_program, Toast.LENGTH_SHORT).show();
            }else {
                finish();
            }

            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentColor", currentColor);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        currentColor = savedInstanceState.getInt("currentColor");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_rb_fst:
                MobclickAgent.onEvent(mContext, "Featured_Man");
                setChannel(1);
                break;

            case R.id.id_rb_snd:
                MobclickAgent.onEvent(mContext, "Featured_Woman");
                setChannel(2);
                break;

            case R.id.id_rb_thd:
                MobclickAgent.onEvent(mContext, "Featured_Publish");
                setChannel(3);
                break;
        }
        // 刷新书架数据
        SPUtil.putBoolean("isRefreshAdapter", true);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.activity_main);
        homeActivity = (HomeActivity)getParent();
        ll_search_img = (LinearLayout)findViewById(R.id.ll_search_img);
        linean_pop = (LinearLayout)findViewById(R.id.linean_pop);
        mFstBtn = (RadioButton)findViewById(R.id.id_rb_fst);
        mFstBtn.setOnClickListener(this);
        mSndBtn = (RadioButton)findViewById(R.id.id_rb_snd);
        mSndBtn.setOnClickListener(this);
        mThdBtn = (RadioButton)findViewById(R.id.id_rb_thd);
        mThdBtn.setOnClickListener(this);

        channel = getResources().getStringArray(R.array.channel);
        popwin = (TextView)findViewById(R.id.popwin);
        tabs = (PagerSlidingTabStrip)findViewById(R.id.tabs);
        pager = (ViewPager)findViewById(R.id.pager);
        pager.setOffscreenPageLimit(5);
        adapter = new MyPagerAdapter(getSupportFragmentManager(), other);

        final int pageMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
        pager.setPageMargin(pageMargin);
        pager.setAdapter(adapter);
        tabs.setViewPager(pager, this, other);
        if (SPUtil.getInt("select_setting", 1) == 3) {
            tabs.setIndicators(book_channels);
        }else if (SPUtil.getInt("select_setting", 1) == 1) {
            tabs.setIndicators(other);
        }else if (SPUtil.getInt("select_setting", 1) == 2) {
            tabs.setIndicators(other);
        }
        choiceState(SPUtil.getInt("select_setting", 1));

        if (SPUtil.getBoolean("lk_direct", true)) {
            homeActivity.setDirection(true);
        }

    }

    @Override
    protected void initData() {
    }

    @Override
    protected void setListener() {
        ll_search_img.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                SPUtil.putBoolean("lk_direct", false);
                homeActivity.setDirection(false);
//                if (ActivityUitl.isNetworkAvailable(mContext)) {
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), BookSearchActivity.class);
                    startActivity(intent);
//                }else {
//                    ToastMgr.showShortToast(R.string.laikan_network_anomaly);
//                }
            }
        });
    }

    // 设置回调接口(监听器)的方法
    public void setYourListener(YourListener yourListener) {
        this.mYourListener = yourListener;

    }

    // 回调接口(监听器)
    public interface YourListener {

        void onSomeChange(boolean flag);
    }

    // TODO viewPage adapter
    public class MyPagerAdapter extends FragmentPagerAdapter {

        private int mChildCount = 0;
        private String[] TITLES;

        public MyPagerAdapter(FragmentManager fm, String[] string) {
            super(fm);
            TITLES = string;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }

        @Override
        public Fragment getItem(int position) {

            return SuperAwesomeCardFragment.newInstance(position);
        }

        @Override
        public int getItemPosition(Object object) {
            if (mChildCount > 0) {
                mChildCount--;
                return POSITION_NONE;
            }
            return super.getItemPosition(object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            Object obj = super.instantiateItem(container, position);
            return obj;
        }

    }

    private void setChannel(int channel){
        SPUtil.putInt("tab_refresh", pager.getCurrentItem());
        SPUtil.putInt("select_setting", channel);
        SPUtil.putInt("current_channel", channel);
        Intent it = new Intent("change_position");
        it.putExtra("position", channel);
        if (SPUtil.getInt("select_setting", 0) != 1 || SPUtil.getInt("select_setting", 0) != 2){
            SPUtil.putBoolean("rank_flush_flag", true);
            tabs.setIndicators(book_channels);
        }

        if (SPUtil.getInt("select_setting", 0) != 1) {
            setResult(1);
        }

        if (SPUtil.getInt("select_setting", 0) != 3) {
            tabs.setIndicators(other);
        }

        if (mYourListener != null) {
            mYourListener.onSomeChange(true);
        }
        sendBroadcast(it);
    }
}